package cn.fl.customer.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.customer.service.ICstManualRelationService;
import cn.fl.customer.vo.CstManualRelationVO;
import com.alibaba.fastjson.JSON;
import fl.customer.facade.customer.condition.CstManualRelationQC;
import fl.customer.facade.framework.constant.DictionaryConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import cn.fl.framework.base.context.CurrentThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

import java.util.*;


/**
 * @Description: 信审添加与客户、供应商、挂靠公司有相关的人员 控制层
 * @author zhangtongtong
 */
@Controller
@RequestMapping("/customer/cstManualRelation")
public class CstManualRelationController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CstManualRelationController.class);

	/**
	 * CstManualRelation 服务层BEAN
	 */
	@Autowired
	private ICstManualRelationService cstManualRelationService;

	/**
	 * 字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("Id");
		String useType = request.getParameter("useType");
		String cstType = request.getParameter("cstType");
		ModelAndView view = new ModelAndView("customer/cstManualRelation/cstManualRelationListPage");
		view.addObject("id", id);
		view.addObject("useType", useType);//1：客户 2：供应商 3：挂靠公司
		view.addObject("cstType", cstType);//1：自然人 2：法人
		BaseLogUtils.info(logger, "toListPage", "跳转到人工干预列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改(新增)页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String Id = request.getParameter("id");
		String cstId = request.getParameter("cstId");
		String useType = request.getParameter("useType");
		String cstType = request.getParameter("cstType");
		String args = request.getParameter("args");
		ModelAndView view = new ModelAndView("customer/cstManualRelation/cstManualRelationModify");
		List<KeyValueVO> relaUserTypeCdList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_GRP_RELA_USER_TYP_CD);
		if (CollectionUtils.isNotEmpty(dictionaryList)) {
			relaUserTypeCdList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				if(sysDictionaryDTO.getCodeAttr1().equals(cstType)){
					KeyValueVO keyValue = new KeyValueVO();
					keyValue.setKey(sysDictionaryDTO.getCode());
					keyValue.setValue(sysDictionaryDTO.getCodeNm());
					relaUserTypeCdList.add(keyValue);
				}
			}
		}
		if(!"4".equals(args)){//修改
			CstManualRelationVO cstManualRelationVO = this.cstManualRelationService.selectById(Long.parseLong(Id));
			view.addObject("cstManualRelation", cstManualRelationVO);
		}

		view.addObject("args", args);
		view.addObject("cstId", cstId);
		view.addObject("useType", useType);
		view.addObject("cstType", cstType);//1：自然人 2：法人
		view.addObject("relaUserTypeCdListJson", JSON.toJSONString(relaUserTypeCdList));//联系人类型

		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改（新增）页面", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
	    String  relaNm = request.getParameter("relaNm");// 关联人姓名/名称
	    String  relaPhone = request.getParameter("relaPhone");// 手机号
	    String  certNo = request.getParameter("certNo");// 证件号码
		String  cstId = request.getParameter("cstId");//关联id
		String  useType = request.getParameter("useType");//1：客户 2：供应商 3：挂靠公司
		String  cstType = request.getParameter("cstType");//1：自然人 2：法人

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		CstManualRelationQC qc = new CstManualRelationQC();
	    if (StringUtils.isNotEmpty(relaNm)) {
			qc.setRelaNm(relaNm);
		}
	    if (StringUtils.isNotEmpty(relaPhone)) {
			qc.setRelaPhone(relaPhone);
		}
	    if (StringUtils.isNotEmpty(certNo)) {
			qc.setCertNo(certNo);
		}
	    if (StringUtils.isNotEmpty(cstId)) {
			qc.setRelaKeyId(Long.parseLong(cstId));
		}
		if (StringUtils.isNotEmpty(useType)) {
			qc.setRelaType(Integer.parseInt(useType));
		}
		if (StringUtils.isNotEmpty(cstType)) {
			qc.setCstTypeCd(Integer.parseInt(cstType));
		}

		page.setCondition(qc);
		Pager searchListPage =this.cstManualRelationService.searchListPage(page);
		List<CstManualRelationVO> list = (List<CstManualRelationVO>) searchListPage.getResultList();
		ListPageVO<CstManualRelationVO> listPage = new ListPageVO<CstManualRelationVO>(list, searchListPage.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(listPage), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.cstManualRelationService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CstManualRelationVO vo = this.cstManualRelationService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String relaNm = request.getParameter("relaNm");
		String relaPhone = request.getParameter("relaPhone");
		String certType = request.getParameter("certType");
		String certNo = request.getParameter("certNo");
		String relaNote = request.getParameter("relaNote");
		String useType = request.getParameter("useType");
		String cstType = request.getParameter("cstType");
		String relaUserTypeCd = request.getParameter("relaUserTypeCd");
		String cstId = request.getParameter("cstId");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        if(StringUtils.isEmpty(cstId)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.error(logger, "add", "获取客户数据,主键不存在.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

		CstManualRelationVO entity = null;
		try {
			entity = new CstManualRelationVO();
			if (StringUtils.isNotEmpty(relaNm)) {
				entity.setRelaNm(relaNm);//关联人姓名/名称
			}
			if (StringUtils.isNotEmpty(relaPhone)) {
				entity.setRelaPhone(relaPhone);//电话
			}
			if (StringUtils.isNotEmpty(certNo)) {
				entity.setCertNo(certNo);//证件号码
			}
            if (StringUtils.isNotEmpty(certType)) {
                entity.setCertType(Integer.parseInt(certType));//证件类型
            }

			if (StringUtils.isNotEmpty(cstId)) {
				entity.setRelaKeyId(Long.parseLong(cstId));//关联类别主键ID-------客户ID、供应商ID、挂靠公司ID
			}
			if (StringUtils.isNotEmpty(useType)) {
                entity.setRelaType(Integer.parseInt(useType));//关联类别--------1：客户 2：供应商 3：挂靠公司
			}
			if (StringUtils.isNotEmpty(cstType)) {
				entity.setCstTypeCd(Integer.parseInt(cstType));//客户类型
			}
			if (StringUtils.isNotEmpty(relaUserTypeCd)) {
				entity.setRelaUserTypeCd(relaUserTypeCd);//联系人类型
			}

            if (StringUtils.isNotEmpty(relaNote)) {
                entity.setRelaNote(relaNote);//备注
            }
			entity.setIsDel(0);
			entity.setIsValid(1);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setCrtTm(new Date());

			Long id = this.cstManualRelationService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String relaNm = request.getParameter("relaNm");
		String relaPhone = request.getParameter("relaPhone");
		String certType = request.getParameter("certType");
		String certNo = request.getParameter("certNo");
		String relaNote = request.getParameter("relaNote");
		String isDel = request.getParameter("isDel");
		String relaUserTypeCd = request.getParameter("relaUserTypeCd");

		DataResultVO result = null;
		if(StringUtils.isNotEmpty(isDel)){
			result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		}else{
			result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		}

		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CstManualRelationVO entity = null;
		try {
			entity = new CstManualRelationVO();
			entity.setId(Long.valueOf(id));

			if (StringUtils.isNotEmpty(relaNm)) {
				entity.setRelaNm(relaNm);//关联人姓名/名称
			}
			if (StringUtils.isNotEmpty(relaPhone)) {
				entity.setRelaPhone(relaPhone);//电话
			}
			if (StringUtils.isNotEmpty(certNo)) {
				entity.setCertNo(certNo);//证件号码
			}
			if (StringUtils.isNotEmpty(certType)) {
				entity.setCertType(Integer.parseInt(certType));//证件类型
			}
			if (StringUtils.isNotEmpty(relaNote)) {
				entity.setRelaNote(relaNote);//备注
			}
			if (StringUtils.isNotEmpty(relaUserTypeCd)) {
				entity.setRelaUserTypeCd(relaUserTypeCd);//联系人类型
			}

			if (StringUtils.isNotEmpty(isDel)) {
				entity.setIsDel(1);//修改为删除状态
				entity.setIsValid(0);//不可用
			}

			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());

			boolean success = this.cstManualRelationService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

